package com.jing.yao.security.handler;

import com.jing.yao.bean.ResponseBean;
import com.jing.yao.code.UserCode;
import com.jing.yao.component.constants.BmsConstants;
import com.jing.yao.i18.MessageSourceHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限没通过
 *
 * @author lirui
 * @since 2020-06-20
 */
public class YaoAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private Logger logger = LoggerFactory.getLogger(YaoAuthenticationEntryPoint.class);

    @Autowired
    private MessageSourceHolder messageSourceHolder;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding(BmsConstants.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        String code = UserCode.USER_TOKEN_EXPIRED;
        ResponseBean responseBean = ResponseBean.builder().code(code).build();
        responseBean.setMessage(messageSourceHolder.getMessage(code));
        response.getWriter().print(new ObjectMapper().writeValueAsString(responseBean));
    }
}
